package com.tidu.controller;

import com.tidu.entry.ESDocument;
import com.tidu.manager.DataSourceManager;
import com.tidu.service.DataSyncService;
import com.tidu.service.ElasticsearchService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/es")
@RequiredArgsConstructor
public class MetaDataSyncController {

    private final ElasticsearchService elasticsearchService;
    private final DataSyncService dataSyncService;
    private final DataSourceManager dataSourceManager;

    @GetMapping("/sync")
    public void sync() {
        try {
            // 创建索引（如果不存在）
            elasticsearchService.createIndexIfNotExists();
            // 同步所有数据到ES
            System.out.println("开始数据同步...");
            dataSyncService.syncAllDataSources();
            System.out.println("数据同步完成");
        } catch (Exception e) {
            System.err.println("系统错误: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                // 关闭资源
                dataSourceManager.shutdown();
            } catch (Exception e) {
                System.err.println("资源关闭失败: " + e.getMessage());
            }
        }
    }

    @GetMapping("/search")
    public List<ESDocument> search(@RequestParam(name = "keyword") String keyword,
                               @RequestParam(name = "size", defaultValue = "10") Integer size) {
        return elasticsearchService.search(keyword, size);
    }
}